package com.madou.dbtool.mysql.manager;

import com.madou.dbtool.relationship.pojo.ConnectionInfo;
import com.madou.inters.util.TipUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 管理多个数据库的数据源
 * @author miukoo
 */
public class ConnectionManagerFactory {

    private static final Map<String, Connection> CONNECTION_MAP = new HashMap<>();
    /**
     * 最大连接次数
     */
    private static final int maxRetry = 2;
    public static Connection getConnection(ConnectionInfo connectionInfo, String database) {
        return getConnection(connectionInfo, database, 0);
    }

    public static void resetConnection(ConnectionInfo connectionInfo, String database) {
        String id = getId(connectionInfo,database);
        Connection connection = CONNECTION_MAP.get(id);
        if(connection!=null){
            try {
                if (!connection.isClosed()) {
                    connection.close();
                }
                CONNECTION_MAP.remove(id);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    private static String getId(ConnectionInfo connectionInfo, String database){
        String id = String.format("%s-%s-%s-%s",connectionInfo.getHost(),connectionInfo.getPort(),connectionInfo.getUsername(),database);
        return id;
    }

    /**
     * 获取连接，并最多获取三次
     * @param connectionInfo
     * @param database
     * @param count
     * @return
     */
    private static Connection getConnection(ConnectionInfo connectionInfo, String database, int count) {
        if(count>maxRetry) {
            return null;
        }
        String id = getId(connectionInfo,database);
        Connection connection = CONNECTION_MAP.get(id);
        if(connection==null) {
            String useSystemProxies = System.getProperty("java.net.useSystemProxies");
            try {
                System.out.println("===========useSystemProxies:"+useSystemProxies);
                System.setProperty("java.net.useSystemProxies", "false");
                String url = String.format("jdbc:mysql://%s:%d/%s?allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=UTF-8&connectTimeout=500&serverTimezone=Asia/Shanghai&useSSL=false", connectionInfo.getHost(), connectionInfo.getPort(), database);
                Class.forName("com.mysql.cj.jdbc.Driver");
                connection = DriverManager.getConnection(url, connectionInfo.getUsername(), connectionInfo.getPassword());
            } catch (Exception e) {
                e.printStackTrace();
                if(count==maxRetry){
                    String mess = e.getMessage();
                    if(mess.contains("The last packet sent successfully to the server was 0 milliseconds ago")){
                        TipUtils.showErrorDialog("如果开启了代理，请关闭后重试！获取数据库连接失败：" + e.getMessage(), "Tips");
                    }else {
                        TipUtils.showErrorDialog("获取数据库连接失败：" + e.getMessage(), "Tips");
                    }
                }else if(count<maxRetry) {
                    return getConnection(connectionInfo, database,count+1);
                }
            }finally {
                if(useSystemProxies!=null) {
                    System.setProperty("java.net.useSystemProxies", useSystemProxies);
                }
            }
        }else{
            try {
                if(connection.isClosed()){
                    connection=null;
                    if(count<maxRetry) {
                        return getConnection(connectionInfo, database,count+1);
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        CONNECTION_MAP.put(id,connection);
        return connection;
    }
}
